package com.mysteel.order.interceptor;

import com.mysteel.common.constant.AuthServerConstant;
import com.mysteel.common.vo.MemberResponseVo;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * ProjectName: mail
 * ClassName: LoginUserInteceptor
 * Description:
 * date: 2021/03/20/020 14:21
 *
 * @author xiaochao
 */
@Component
public class LoginUserInterceptor implements HandlerInterceptor {

    public static ThreadLocal<MemberResponseVo> threadLocal = new ThreadLocal<>();

    public static Set<String> excludePaths = new HashSet<>();

    @PostConstruct
    public void init(){
        excludePaths.add("/order/order/orderSn");
        excludePaths.add("/aliPay/notify");
    }


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        AntPathMatcher pathMatcher = new AntPathMatcher();
        String requestURI = request.getRequestURI();
        /**
         * 在白名单路径中的请求则不拦截
         */
        boolean match = excludePaths.stream().anyMatch(path -> pathMatcher.match(path, requestURI));
        if (match){
            return true;
        }


        HttpSession session = request.getSession();
        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_USER_DATA);
        if (attribute != null){
            // 用户已登录
            MemberResponseVo memberResponseVo = (MemberResponseVo) attribute;
            threadLocal.set(memberResponseVo);
            return true;
        }
        session.setAttribute("msg","请先登录");
        response.sendRedirect("http://auth.xcmail.com/login.html");
        return false;
    }
}
